package com.szf.task.service.api;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.szf.base.bean.SinlogConstants;
import com.szf.base.exception.GenericException;
import com.szf.task.entity.AppInfo;
import com.szf.task.entity.Task;
import com.szf.util.MapUtil;
import com.szf.util.StringUtil;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.utils.QHttpClient;

public abstract class AbstractApiInterface implements ApiInterface, Runnable {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected OAuthV2 oauth;
	protected Task task;
	protected AppInfo app;

	protected boolean stop = false;

	protected Map<String, String> params = new HashMap<String, String>();

	protected String format = "json";
	protected String clientip = "127.0.0.1";

	protected String apiRs;

	public AbstractApiInterface(Task task, AppInfo app) {
		super();
		this.task = task;
		this.app = app;

		if (!StringUtil.isEmpty(task.getParam())) {
			for (String param : task.getParam().split(";")) {
				try {
					String[] kv = param.split("=");
					params.put(kv[0], kv[1]);
				} catch (Exception e) {

				}
			}
		}

	}

	public void auth() throws Exception {
		oauth = new OAuthV2();
		oauth.setClientId(app.getAppKey());
		oauth.setClientSecret(app.getAppSecret());
		oauth.setRedirectUri(SinlogConstants.AUTH_CALLBACK + "?taskid="
				+ task.getTaskId());

		QHttpClient qHttpClient = new QHttpClient(2, 2, 5000, 5000, null, null);
		OAuthV2Client.setQHttpClient(qHttpClient);
		openBrowser(oauth);
	}

	@Override
	public void run() {
		try {
			while (true) {
				if (!stop) {
					if (oauth == null) {
						auth();
					} else {
						if (get()) {
							afterGet();
						}
						Thread.sleep(4000);
					}
				} else {
					Thread.sleep(10000);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			stop = true;
			oauth = null;
		}
	}

	public void openBrowser(OAuthV2 oAuth) throws Exception {

		String authorizationUrl = OAuthV2Client.generateAuthorizationURL(oAuth);

		// 调用外部浏览器
		if (!java.awt.Desktop.isDesktopSupported()) {
			throw new GenericException("Desktop is not supported (fatal)");
		}
		java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
		if (desktop == null
				|| !desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
			throw new GenericException(
					"Desktop doesn't support the browse action (fatal)");
		}
		desktop.browse(new URI(authorizationUrl));

		stop = true;
	}

	@Override
	public void authBack(Map<String, String> param) throws Exception {
		String code = MapUtil.getMap(param, "code");
		String openid = MapUtil.getMap(param, "openid");
		String openkey = MapUtil.getMap(param, "openkey");
		StringBuilder sb = new StringBuilder();
		sb.append("code=").append(code);
		sb.append("&openid=").append(openid);
		sb.append("&openkey=").append(openkey);

		OAuthV2Client.parseAuthorization(sb.toString(), oauth);
		if (oauth.getStatus() == 2) {
			stop = true;
			throw new GenericException("error auth!");
		}

		// 换取access token
		oauth.setGrantType("authorize_code");
		OAuthV2Client.accessToken(oauth);
		if (oauth.getStatus() == 3) {
			stop = true;
			throw new GenericException("get access token error!");
		}

		stop = false;
	}

	@Override
	public void stop() {
		stop = true;
		oauth = null;

	}

	@Override
	public boolean isStop() {
		return stop;
	}

	@Override
	public void restart() {
		stop = false;
	}
}
